package com.seestech.sell.web.permission;

import com.github.pagehelper.Page;
import com.seestech.sell.common.utils.Constants;
import com.seestech.sell.common.utils.ResponseUtils;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.domain.model.AgentGroup;
import com.seestech.sell.domain.model.Company;
import com.seestech.sell.domain.model.Role;
import com.seestech.sell.domain.model.User;
import com.seestech.sell.domain.model.enums.StatusEnums;
import com.seestech.sell.service.IAgentGroupService;
import com.seestech.sell.service.ICompanyService;
import com.seestech.sell.service.IRoleService;
import com.seestech.sell.service.IUserService;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

/**
 * @description 权限管理
 * Created by idiot on 2016/12/15.
 */
@Controller
@RequestMapping(value = "permission/user")
public class PUserController extends SuperController {
    private static final Logger logger = LoggerFactory.getLogger(PUserController.class);

    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;
    @Resource
    private IAgentGroupService agentGroupService;
    @Resource
    private ICompanyService companyService;

    /**
     * 权限之用户相关
     * */
    //加载page页面
    @RecordLog(value = "加载管理员用户页面")
    @RequiresPermissions(value = "permission:user:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toPage(){
        return "permission/user/page";
    }

    //加载data页面
    @RequestMapping(value = "data", method = RequestMethod.POST)
    public String data(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize, User info, Model model){
        User user = getUser();
        if (user == null){
            logger.error("用户信息已经失效，请重新登录");
            return "login";
        }
        info.setCreateUser(user.getUserId());
        info.setStatus(StatusEnums.VALID.getValue());
        Page<User> lists = userService.getAllAdminUsers(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        //获取该用户信息
        User item = userService.getUserByUserId(user.getUserId());
        if(!lists.contains(item)){
            lists.add(item);
        }
        //获取该用户管理的企业信息
        List<Company> companys = companyService.getManageCompanyByUserId(user.getUserId());
        List<Long> companyIds = new ArrayList<>();
        for (Company company : companys){
            companyIds.add(company.getId());
        }
        //结果集 大于 0
        if (companyIds.size() > 0){
            //根据企业信息编号  获取用户信息
            List<User> users = userService.getUsersByCompanyIds(companyIds);
            lists.removeAll(users);     //求并集
            lists.addAll(users);
        }
        //JSONArray jsonArray = (JSONArray) JSON.toJSON(lists);
        model.addAttribute("lists", lists);
        //model.addAttribute("items", jsonArray);
        return "permission/user/data";
    }

    //加载用户信息编辑页面
    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    public String toAdd(Model model){
        return "permission/user/update";
    }

    //编辑用户信息
    @RecordLog(value = "修改管理员用户信息")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public void update(User info){
        User item = getUser();
        if(item == null){
            logger.error("修改管理员用户信息====>>>>>用户信息失效，请重新登录");
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "用户信息失效，请重新登录");
            return;
        }
        User user = userService.getUserByName(info.getUserName());
        //userId为空/0时表示   新增操作
        if(info.getUserId() == null){
            //查询用户信息
            if(user != null){
                ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "用户名存在，新增失败");
            }else {
                info.setCreateUser(item.getUserId());   //设置添加用户id
                userService.insert(info);
                ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "新增用户信息成功");
            }
        }else {     //修改操作
            if(user != null){
                if(!user.getUserId().equals(info.getUserId())){
                    ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "用户名存在,修改失败");
                    return;
                }
            }
            info.setUpdateUser(item.getUserId());   //设置修改用户id
            userService.update(info);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "修改用户信息成功");
        }
    }

    //加载编辑页面
    @RequestMapping(value = "{userId}/toUpdate", method = RequestMethod.GET)
    public String toUpdate(@PathVariable("userId") long userId, Model model){
        User user = userService.getUserByUserId(userId);
        model.addAttribute("user",user);
        return "permission/user/update";
    }

    //删除用户信息
    @RecordLog(value = "删除管理员信息")
    @RequestMapping(value = "{userId}/delete", method = RequestMethod.POST)
    public void delete(@PathVariable("userId") long userId){
        userService.delete(userId);
        ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"删除用户信息成功");
    }

    //前往授权角色页面
    @RequestMapping(value = "{userId}/toGrantRoles", method = RequestMethod.GET)
    public String toGrantRoles(@PathVariable("userId") Long userId, Model model){
        //根据userId获取用户已经拥有的角色信息
        List<Role> userRoles = roleService.getRolesByUserId(userId);
        //获取所有的角色信息
        List<Role> roles = roleService.getAllValidRoles();
        model.addAttribute("userRoles", userRoles);
        model.addAttribute("roles", roles);
        model.addAttribute("userId", userId);
        return "permission/user/grantRoles";
    }

    //给用户分配终端组
    @RequestMapping(value = "{userId}/toGrantAgentGroups", method = RequestMethod.GET)
    public String toGrantAgentGroups(@PathVariable("userId") Long userId, Model model){
        User user = getUser();
        if(user == null){
            logger.error("给用户分配终端组======>>>>>>>>用户信息失效，请重新登录");
            return "login";
        }
        //根据userId获取用户已经拥有的终端分组信息
        List<AgentGroup> userAgentGroups = agentGroupService.getAllValidAgentGroupsByUserId(userId);
        AgentGroup info = new AgentGroup();
        //获取这个用户所在企业相关的用户信息
        Set<Long> userIds = getUserIds(user);
        userIds.add(user.getUserId());
        info.setUserIds(userIds);
        info.setCreateUser(null);
        info.setStatus(StatusEnums.VALID.getValue());
        //获取所有的终端分组信息
        List<AgentGroup> agentGroups = agentGroupService.getAllValidAgentGroups(info);
        model.addAttribute("userAgentGroups", userAgentGroups);
        model.addAttribute("agentGroups", agentGroups);
        model.addAttribute("userId", userId);
        return "permission/user/grantAgentGroups";
    }

}
